package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import com.mysql.cj.util.StringUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
/**
 *登录校验过滤器
 * 每次请求都要经过的方法
 */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.登入请求要放行
        //2.获取请求路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestPath = request.getRequestURI();
        log.info("拦截的请求路径是{}",requestPath);
        //只有login才放行
        if(requestPath.endsWith("/login")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //其他的请求要获取token，并校验token是否有效
        String token = request.getHeader("token");
        log.info("获取的token是{}",token);
       // 判断token是否为空
        if(!StringUtils.isNullOrEmpty(token)){
            //不为空，解析token
            try {
                Claims claims = JwtUtils.parseJWT(token);
                log.info("解析的token是{}",claims);
                //获取当前登录用户id
                Integer userId = claims.get("id", Integer.class);
                //保存当前登录用户id
                CurrentHolder.setCurrentId(userId);
                //把当前登录用户保存到当前线程中
                //放行
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            } catch (Exception e) {
                log.error("解析token失败了", e);
            } finally {
                //使用后移除线程变量
                CurrentHolder.remove();
            }
        }
        //没有token或者解析失败，返回401
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
    }
}

